extends Node2D

signal shoot
signal target_on_sight

class_name Weapon


export (String) var weapon_name
export (float) var rotation_max = 90.0
export (int) var rpm = 100
export (float) var rotation_speed = 50.0 # deg/sec
export (int) var lasersight_size = 50
export (PackedScene) var BulletScene

onready var Muzzle : Position2D = $MuzzlePosition
onready var Pivot : Position2D = $RotationPoint

var angle_deg setget set_angle

var _can_fire = true
var _can_rot = true
var angle_target : float

func is_within(a, b, e):
	return a >= (b - e) and a <= (b + e)

func _ready():
	set_angle(0)
	$ShootTimer.wait_time = 60.0 / rpm
	$RotationPoint/PivotTimer.wait_time = 1.0 / rotation_speed # ms/deg

func _physics_process(delta):
	#set_angle(lerp(angle_deg, 0, delta / 100 * rotation_speed))
	if angle_target and _can_rot:
		if not is_within(angle_deg, angle_target, 5):
			if angle_target > angle_deg:
				set_angle(angle_deg + 1)
			else:
				set_angle(angle_deg - 1)
			_can_rot = false
			$RotationPoint/PivotTimer.start()
		else:
			emit_signal("target_on_sight")
#	$Label.text = String(angle_deg) + "\n" + String(angle_target)

func set_angle(deg):
	angle_deg = fmod(deg, 360)
	angle_deg = clamp(angle_deg, -rotation_max, rotation_max)
	var angle_rad := deg2rad(angle_deg)
	Muzzle.position = Pivot.position + Vector2.RIGHT.rotated(angle_rad) * 8
	$LaserSight.points = [Pivot.position, Muzzle.position]
	Pivot.rotation = Pivot.position.direction_to(Muzzle.position).angle()

func aim_at_pos(pos: Vector2):
	var dir = Pivot.position.direction_to(pos)
	angle_target = clamp(fmod(rad2deg(dir.angle()), 360), -rotation_max, rotation_max)

func shoot():
	if BulletScene and _can_fire:
		var bullet_instance : Bullet = BulletScene.instance()
		bullet_instance.direction = Pivot.position.direction_to(Muzzle.position).normalized()
		bullet_instance.position = Muzzle.position
		bullet_instance.scale = Vector2(0.5, 0.5)
		emit_signal("shoot", bullet_instance)
		_can_fire = false
		if bullet_instance is Laser:
			bullet_instance.connect("laser_end", self, "_on_Laser_laser_end")
			bullet_instance.start_point = position
		$ShootTimer.start()

#func _input(event):
#	if event is InputEventMouseButton:
#		if event.pressed and event.button_index == BUTTON_LEFT:
#			aim_at_pos(get_global_mouse_position())

func get_sprite() -> AtlasTexture:
	var tex := AtlasTexture.new()
	tex.atlas = $RotationPoint/Sprite.texture
	tex.region = Rect2(0, 0, 8, 8)
	return tex

func _on_ShootTimer_timeout():
	_can_fire = true


func _on_PivotTimer_timeout():
	_can_rot = true


func _on_Weapon_target_on_sight():
	shoot()

func _on_Laser_laser_end():
	_can_fire = false
	$ShootTimer.start()
